import { ipcRenderer, contextBridge, PrintToPDFOptions } from "electron";

// --------- Expose some API to the Renderer process ---------
contextBridge.exposeInMainWorld("electronAPI", {
  // 文件系统API
  fs: {
    readFile: (filePath: string) => ipcRenderer.invoke("fs:readFile", filePath),
    writeFile: (filePath: string, content: string) =>
      ipcRenderer.invoke("fs:writeFile", filePath, content),
    createDirectory: (dirPath: string) =>
      ipcRenderer.invoke("fs:createDirectory", dirPath),
    readDirectory: (dirPath: string) =>
      ipcRenderer.invoke("fs:readDirectory", dirPath),
    deleteFile: (filePath: string) =>
      ipcRenderer.invoke("fs:deleteFile", filePath),
    deleteDirectory: (dirPath: string) =>
      ipcRenderer.invoke("fs:deleteDirectory", dirPath),
    rename: (oldPath: string, newPath: string) =>
      ipcRenderer.invoke("fs:rename", oldPath, newPath),
  },

  // 对话框API
  dialog: {
    openFile: () => ipcRenderer.invoke("dialog:openFile"),
    saveFile: (defaultPath?: string) =>
      ipcRenderer.invoke("dialog:saveFile", defaultPath),
    selectDirectory: () => ipcRenderer.invoke("dialog:selectDirectory"),
  },

  // 文件操作API
  file: {
    newFile: () => ipcRenderer.invoke("file:new"),
    exportPDF: (filePath: string, options: PrintToPDFOptions) =>
      ipcRenderer.invoke("file:export-pdf", filePath, options),
  },

  // IPC通信API
  on: (channel: string, listener: (...args: any[]) => void) => {
    return ipcRenderer.on(channel, (event, ...args) =>
      listener(event, ...args)
    );
  },
  off: (channel: string, listener?: (...args: any[]) => void) => {
    if (!listener) {
      return ipcRenderer.removeAllListeners(channel);
    }
    return ipcRenderer.off(channel, listener);
  },
  send: (channel: string, ...args: any[]) => {
    return ipcRenderer.send(channel, ...args);
  },
  invoke: (channel: string, ...args: any[]) => {
    return ipcRenderer.invoke(channel, ...args);
  },

  // You can expose other APIs you need here.
  // ...
});
